package com.geovis.emergency.spd.biz.agora;

import cn.hutool.core.lang.Assert;
import com.geovis.common.core.util.NumberUtil;
import com.geovis.emergency.spd.biz.agora.lib.RtcTokenBuilder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 声网 token
 * </p>
 *
 * @author 王响
 * @since 2022-05-05
 */
@Setter
@Getter
@Component
@RequiredArgsConstructor
public class AgoraTokenUtil {

    private final AgoraProperties agoraProperties;

    private final RedisTemplate redisTemplate;

    private final String CACHE_KEY = "agora:accountId";

    private final Long MAX_ACCOUNT_ID = 9999999999L;

    private final String pattern = "0000000000";

    /**
     * 生成token
     *
     * @param channelId 会议id
     * @return
     */
    public AgoraTokenDTO getToken(String channelId) {
        Assert.notBlank(channelId, "会议id或频道id不能为空");
        Long accountId = redisTemplate.opsForValue().increment(CACHE_KEY);
        if (accountId > MAX_ACCOUNT_ID) {
            redisTemplate.opsForValue().decrement(CACHE_KEY, MAX_ACCOUNT_ID);
            accountId = redisTemplate.opsForValue().increment(CACHE_KEY);
        }

        String uid = String.valueOf(accountId);

        RtcTokenBuilder rtcTokenBuilder = new RtcTokenBuilder();
        int timestamp = (int) (System.currentTimeMillis() / 1000 + agoraProperties.getExpiredAt());
        String token = rtcTokenBuilder.buildTokenWithUserAccount(agoraProperties.getAppId(), agoraProperties.getAppCertificate(),
                channelId, uid, RtcTokenBuilder.Role.Role_Publisher, timestamp);
        return new AgoraTokenDTO().setToken(token).setAppId(agoraProperties.getAppId()).setChannelId(channelId).setUid(uid);
    }


}
